package com.spring.security.web.service.impl;

import com.spring.security.core.generic.GenericDao;
import com.spring.security.core.generic.GenericServiceImpl;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.web.dao.RoleMapper;
import com.spring.security.web.dao.UserMapper;
import com.spring.security.web.model.User;
import com.spring.security.web.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户Service实现类
 *
 * @author StarZou
 * @since 2014年7月5日 上午11:54:24
 */
@Service
public class UserServiceImpl extends GenericServiceImpl<User, Long> implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;

    @Override
    public int insert(User model,String role_id) {
        int u = userMapper.insertSelective(model);
        Map<String,String> m = new HashMap<String,String>();
        m.put("id",ApplicationUtils.randomUUID());
        m.put("user_id",model.getId());
        m.put("role_id",role_id);
        int r = roleMapper.insertUserRole(m);
        int ret = 0;
        if(u==1&&r==1){
            ret = 1;
        }
        return ret;
    }

    @Override
    public int update(User model) {
        return userMapper.updateByPrimaryKeySelective(model);
    }

    @Override
    public int delete(Long id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public User authentication(User user) {
        return userMapper.authentication(user);
    }

    @Override
    public User selectById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public GenericDao<User, Long> getDao() {
        return userMapper;
    }

    @Override
    //@Transactional  //事务支持
    public User selectByUsername(String username) {
        User user = new User();
        user.setUsername(username);
        List<User> list = userMapper.selectByWhereStr(user);
        if(ApplicationUtils.isNotNull(list)&&list.size()!=0)
        return list.get(0);
        return null;
    }

}
